﻿using IdentityServer4.SqlSugarCore.DbContexts;
using IdentityServer4.SqlSugarCore.Interfaces;
using IdentityServer4.SqlSugarCore.TokenCleanups;
using IdentityServer4.Stores;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;

namespace IdentityServer4.SqlSugarCore
{
    public static class IdentityServerSqlSugarBuilderExtensions
    {
        /// <summary>
        /// 配置Sugar接口和实现(默认使用SqlServer)
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="storeOptionsAction">存储配置信息</param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddSugarStore(
            this IIdentityServerBuilder builder,
            IConfiguration configuration)
        {
            var options = new SugarStoreOptions();
            configuration.Bind("IdentityServerStoreOptions", options);
            builder.Services.AddSingleton(options);

            builder.Services.AddTransient<DbContext>();
            builder.Services.AddTransient<IClientStore, ClientStore>();
            builder.Services.AddTransient<IResourceStore, ResourceStore>();
            builder.Services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();

            builder.Services.AddTransient<IPersistedGrants, SugarPersistedGrants>();
            builder.Services.AddSingleton<TokenCleanup>();
            builder.Services.AddSingleton<IHostedService, TokenCleanupHost>();
            return builder;
        }
    }
}
